package com.yh.correct.controller;

import java.io.*;
import java.sql.Timestamp;
import java.util.*;

import com.yh.common.utils.ExcelUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageInfo;
import com.yh.correct.model.ResultData;
import com.yh.correct.model.SysPermission;
import com.yh.correct.model.SysRole;
import com.yh.correct.model.vo.Tree;
import com.yh.correct.service.ISysPermissionService;
import com.yh.correct.service.ISysRoleService;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 角色管理控制层
 * 
 * @author Administrator
 *
 */
@RestController
@RequestMapping(value = "/sysrole")
public class SysRoleController {

	// 日志
	private static Logger logger = LogManager.getLogger(SysRoleController.class);

	// 角色服务层接口
	@Autowired
	private ISysRoleService roleService;

	// 权限服务层接口
	@Autowired
	private ISysPermissionService permissionService;

	/**
	 * 跳转到角色管理页面
	 * 
	 * @return
	 */
	@RequestMapping(value = "/show")
	public ModelAndView toShow() {
		ModelAndView mv = new ModelAndView("/system/sysrole");
		return mv;
	}

	/**
	 * 动态查找角色分页
	 * @param roleName
	 * @param pageNum
	 * @param pageSize
	 * @return
	 */
	@RequestMapping(value = "/search")
	public ResultData searchRole(String roleName, Integer pageNum, Integer pageSize) {
		Map<String, Object> condition = new HashMap<String, Object>();
		condition.put("pageNum", pageNum);
		condition.put("pageSize", pageSize);
		condition.put("roleName", roleName);
		PageInfo<Object> pageInfo = null;
		try {
			pageInfo = roleService.findListByCondition(condition);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		List<Object> list = new ArrayList<Object>();
		list.add(pageInfo);
		ResultData rd = new ResultData();
		rd.setCode(0);
		rd.setMessage("查询成功！");
		rd.setData(list);
		return rd;
	}

	
	/**
	 * 跳转到增加角色页面
	 * @return
	 */
	@RequestMapping(value = "/toAdd")
	public ModelAndView toAddRole() {
		/*重构，把查询所有权限方法给取点了*/
		ModelAndView mv = new ModelAndView("/system/sysrole_add");

		return mv;
}

	/**
	 * 增加角色
	 * @param role
	 * @param strArr
	 * @return
	 */
	@RequestMapping(value = "/doAdd")
	public ResultData doAddRole(SysRole role, String strArr) {
		//jack-json 把json字符串转成int数组
		ObjectMapper objectMapper = new ObjectMapper();
		Integer[] perArr = null;
		try {
			perArr = objectMapper.readValue(strArr, Integer[].class);
		} catch (JsonParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (JsonMappingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		int i = 0;
		try {
			role.setCreateTime(new Timestamp(System.currentTimeMillis()));
			/*重构标记，代码不严谨,角色管理中新增角色,无论有没有角色，都会新增权限，不符合逻辑*/
			if(StringUtils.isNotBlank(strArr)&&role.getRoleName().length()>0){
				i = roleService.insertSysRole(role, perArr);
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		ResultData rd = new ResultData();
		if (i>0) {
			rd.setCode(0);
			rd.setMessage("增加成功！");
			return rd;
		} else {
			rd.setCode(4001);
			rd.setMessage("增加失败！");
			return rd;
		}
	}
	
	/**
	 * 删除角色
	 * @param role
	 * @return
	 */
	@RequestMapping(value="/doDel")
	public ResultData doDelRole(SysRole role){
		int i=0;
		try {
			i=roleService.deleteSysRole(role);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		ResultData rd = new ResultData();
		if (i>0) {
			rd.setCode(0);
			rd.setMessage("删除成功！");
			return rd;
		} else {
			rd.setCode(4001);
			rd.setMessage("删除失败！");
			return rd;
		}
		
	}
	
	/**
	 * 跳转到更新角色页面
	 * @param role
	 * @return
	 */
	@RequestMapping(value="/toEdit")
	public ModelAndView toEditRole(SysRole role){
		Map<String,Object> roleObj=null;
		try {
			roleObj=roleService.getSysRole(role);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		ModelAndView mv=new ModelAndView("/system/sysrole_edit");
		mv.addObject("roleObj", roleObj);
		return mv;
	}
	
	/**
	 * 获取权限列表（含角色对象的权限状态）
	 * @param role
	 * @return
	 */
	@RequestMapping(value="/getRoleTree")
	public ResultData getRoleTree(SysRole role){
		Map<String,Object> roleObj=null;
		List<Tree> allList=null;
		try {
			roleObj=roleService.getSysRole(role);
			List<SysPermission> roleList=(List<SysPermission>) roleObj.get("permissions");
			allList=permissionService.findTreeList();
			for(Tree a:allList){
				for(SysPermission r:roleList){
					if(a.getId()==r.getId()){
						a.setChecked(true);
					}
				}
			}
			roleObj.put("permissions", allList);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		ResultData rd = new ResultData();
		rd.setCode(0);
		rd.setMessage("查询成功！");
		rd.setData(allList);
		return rd;
	}
	
	/**
	 * 更新角色
	 * @param role
	 * @param strArr
	 * @return
	 */
	@RequestMapping(value = "/doEdit")
	public ResultData doEditRole(SysRole role, String strArr) {
		//jack-json 把json字符串转成int数组
		ObjectMapper objectMapper = new ObjectMapper();
		Integer[] perArr = null;
		try {
			perArr = objectMapper.readValue(strArr, Integer[].class);
		} catch (JsonParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (JsonMappingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		int i = 0;
		try {
			role.setCreateTime(new Timestamp(System.currentTimeMillis()));
			i = roleService.updateSysRole(role, perArr);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		ResultData rd = new ResultData();
		if (i>0) {
			rd.setCode(0);
			rd.setMessage("修改成功！");
			return rd;
		} else {
			rd.setCode(4001);
			rd.setMessage("修改失败！");
			return rd;
		}
	}
	
	
	/**
	 * 跳转到角色详细页面
	 * @param role
	 * @return
	 */
	@RequestMapping(value="/detail")
	public ModelAndView toDetailRole(SysRole role){
		Map<String,Object> roleObj=null;
		try {
			roleObj=roleService.getSysRole(role);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		ModelAndView mv=new ModelAndView("/system/sysrole_detail");
		mv.addObject("roleObj", roleObj);
		return mv;
	}


	/*
	* 批量删除
	* */
	@RequestMapping(value="/doDelRoleAll")
	public ResultData doDelRoleAll(String selectedRow){
		//jack-json 把json字符串转成int数组
		ObjectMapper objectMapper = new ObjectMapper();
		Integer[] perArr = null;
		try {
			perArr = objectMapper.readValue(selectedRow, Integer[].class);
		} catch (JsonParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (JsonMappingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		int i =0;
		SysRole role=null;

		if(selectedRow!=null){
			for(Integer j:perArr){
				role=new SysRole();
				role.setId(j);
				try {
					i=roleService.deleteSysRole(role);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
		ResultData rd = new ResultData();
		if (i>0) {
			rd.setCode(0);
			rd.setMessage("删除成功！");
			return rd;
		} else {
			rd.setCode(4001);
			rd.setMessage("删除失败！");
			return rd;
		}

	}


	/**
	 * 导出excel表格
	 */
	@RequestMapping(value = "/exportExcel")
	public String download(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String fileName = "办理入矫人员excel文件";
		// 填充projects数据
		List<Map<String, Object>> projects = createData();
		List<Map<String, Object>> list = createExcelRecord(projects);
		String columnNames[] = { "序号", "角色名称", "角色描述", "创建时间", "状态"};// 列名
		String keys[] = { "id","roleName","roleDesc","createTime","status"};// map中的key
		ByteArrayOutputStream os = new ByteArrayOutputStream();
		try {
			ExcelUtil.createWorkBook(list, keys, columnNames).write(os);
		} catch (IOException e) {
			e.printStackTrace();
		}
		byte[] content = os.toByteArray();
		InputStream is = new ByteArrayInputStream(content);
		// 设置response参数，可以打开下载页面
		response.reset();
		response.setContentType("application/vnd.ms-excel;charset=utf-8");
		response.setHeader("Content-Disposition",
				"attachment;filename=" + new String((fileName + ".xls").getBytes(), "iso-8859-1"));
		ServletOutputStream out = response.getOutputStream();
		BufferedInputStream bis = null;
		BufferedOutputStream bos = null;
		try {
			bis = new BufferedInputStream(is);
			bos = new BufferedOutputStream(out);
			byte[] buff = new byte[2048];
			int bytesRead;
			while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
				bos.write(buff, 0, bytesRead);
			}
		} catch (final IOException e) {
			throw e;
		} finally {
			if (bis != null)
				bis.close();
			if (bos != null)
				bos.close();
		}
		return null;
	}


	private List<Map<String,Object>> createData() throws Exception {

		List<Map<String,Object>> list=roleService.getAllRole();
		return list;
	}
	private List<Map<String, Object>> createExcelRecord(List<Map<String,Object>> projects) {
		List<Map<String, Object>> listmap = new ArrayList<Map<String, Object>>();
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("sheetName", "sheet1");
		listmap.add(map);
		Map<String,Object> object=null;
		for (int j = 0; j < projects.size(); j++) {
			object=projects.get(j);
			Map<String, Object> mapValue = new HashMap<String, Object>();
			mapValue.put("id", object.get("id"));
			mapValue.put("roleName", object.get("roleName"));
			mapValue.put("roleDesc", object.get("roleDesc"));
			mapValue.put("createTime", object.get("createTime"));
			mapValue.put("status", object.get("status"));
			listmap.add(mapValue);
		}
		return listmap;
	}





}
